const lodash = require('lodash')
const loginFns = require("../common/login")
import { pageFns } from '../utils/pageHelper'
import { funcFns } from '@/puppeteer/utils/funtion'
import { ArticleDao } from '@/dao/articleDao'

const SELECTORS = { "INPUTBOX": ["div[aria-label=\"Post text\"]"], "UPLOADBOX": ["input[data-testid=\"fileInput\"]"], "COMFIRMBTNS": ["div[role=\"dialog\"] div[data-testid=\"tweetButtonInline\"]", "div[role=\"dialog\"] div[data-testid=\"tweetButton\"]", "div[role=\"dialog\"] span::-p-text(\"Post\")"], "DIALOGBOX": ["div[role=\"dialog\"]"] }
// 发布
async function startPost(page, content, files, selectors) {
    /**
    * @description TYPING INPUT STATUS METHOD
    */
    let res = await pageFns.deepRetry(selectors.INPUTBOX, page, async (selector, page) => {
        let e = await page.waitForSelector(selector)
        console.log("INPUTBOX", e)
        await page.focus(selector)
        await page.type(selector, funcFns.ellipsisContent(content, 276))
    }, { page: page, timeout: 10 * 1000 })
    if (res.err) {
        return res
    }
    /**
    * @description UPLOAD IMAGE STATUS METHOD
    */
    postFiles = files.filter(item => item.match(/\.(png|jpeg|jpg)$/))
    if (postFiles.length <= 0) {
        postFiles = files.filter(item => item.match(/\.(mp4)$/))
        postFiles = files.length <= 0 ? files : files.slice(0, 1)
    } else {
        postFiles = files.length <= 4 ? files : files.slice(0, 4)
    }
    res = await pageFns.deepRetry(selectors.UPLOADBOX, page, async (selector, page) => {
        await page.waitForSelector(selector)
        await pageFns.fileUpload({
            page,
            element: selector,
            files: postFiles
        })
    }, { page: page, wait: 1 * 1000 })
    if (res.err) {
        return res
    }
    /**
     * @description WAIT STATUS METHOD
     */
    res = await pageFns.deepRetry(selectors.COMFIRMBTNS, page, async (selector, page) => {
        await page.waitForSelector(selector)
        await page.click(selector)
        await pageFns.delay(4000)
        await page.waitForFunction((selector) => {
            return !document.querySelector(selector);
        }, {}, selectors.DIALOGBOX);
    }, { page: page })
    if (res.err) {
        return res
    }
    return { data: "发布成功" }
}

const LOGINS = {
    LOGINBTNS: [],
    USERNAMES: ['input[name="text"]'],
    NEXTSTEPS: ['span::-p-text("下一步")'],
    PASSWORDS: ['input[name="text"]', 'input[name="password"]'],
    COMFIRMBTNS: ['button[data-testid="LoginForm_Login_Button"]', 'span::-p-text("下一步")', 'span::-p-text("登录")'],
    UNLOGINFLAGS: ['span::-p-text("登录")']
}

async function goPost(page, task, article, rule) {
    let selectors = JSON.parse(rule.codeRule)
    if (lodash.isEmpty(selectors)) {
        return { err: "找不到发布规则:" + task.id }
    }
    let res = await loginFns.checkLogin(page, task, LOGINS)
    if (res.err) {
        console.log("goPost.checkLogin", res)
        return res
    }
    // 收集图片
    try {
        let dataFields = JSON.parse(task.dataFields)
        if (lodash.isEmpty(dataFields)) {
            return { err: "没有指定的数据" }
        }
        let aiResult = JSON.parse(article.aiResult)
        let contents = []
        for (let dataField of dataFields) {
            contents.push(aiResult[task.lang][dataField])
        }
        console.log(dataFields, article, task.lang)
        let images = funcFns.getImageAndVideos(ArticleDao.folderPath(article))
        return await startPost(page, contents.join("."), images, selectors)
    } catch (err) {
        console.log("goPost", err)
        return { err: err }
    }
}

export { goPost }